import {
	IParam,
	IUIActionResult,
	IActionModel,
	IContext,
	IAbility,
	IHttpResponse,
	deepCopy,
	IViewAbility,
	srfpluralize,
	hasFunction,
	formatUrlString,
    IRedirectInput,
    transformDoData
} from '@/core';
import { Http } from '@/http';
import { EntityUIServiceBase } from '../entity-ui-service-base';
import GridViewLoadUILogic from './grid-view-load-ui-logic';
import OpenYuQueUILogic from './open-yu-que-ui-logic';


/**
 * 订单UI服务对象基类
 * 基于template/src/ui-service/{{appEntities}}/{{appEntities}}-ui-service-base.ts.hbs生成
 *
 * @export
 * @class IBIZOrderUIServiceBase
 * @extends {UIService}
 */
export class IBIZOrderUIServiceBase extends EntityUIServiceBase {

	/**
   * Creates an instance of IBIZOrderUIServiceBase
   * 
   * @param {*} [opts={}]
   * @memberof IBIZOrderUIServiceBase
   */
  constructor(opts: IParam = {}) {
    super(opts);
    this.appDeKeyFieldName = 'ibizorderid';
		// 是否启用主状态
		this.isEnableDEMainState = true;
		// 主状态属性集合
		this.mainStateFields = ['orderstate'];
    // 主状态集合Map
      this.allDeMainStateMap.set('10', '10');
      this.allDeMainStateMap.set('30', '30');
      this.allDeMainStateMap.set('40', '40');
      // 主状态操作标识Map
      this.allDeMainStateOPPrivsMap.set(
			'10',
			Object.assign({ 'CREATE':1,'DELETE':1,'READ':1,'UPDATE':1 }, {  })
		);
      this.allDeMainStateOPPrivsMap.set(
			'30',
			Object.assign({ 'CREATE':1,'DELETE':1,'READ':1,'UPDATE':1 }, {  })
		);
      this.allDeMainStateOPPrivsMap.set(
			'40',
			Object.assign({ 'CREATE':1,'DELETE':1,'READ':1,'UPDATE':1 }, {  })
		);
  	}


	/**
	 * 单数据主键保存
	 *
	 * @param {*} params
	 * @memberof IBIZOrderUIServiceBase
	 */
  public async BUIAction1(
    uiContext: IContext,
    uiViewParams: IParam,
    uiData: IParam[],
    event: MouseEvent,
    ability: IAbility
  ): Promise<IUIActionResult> {
        const actionModel: IActionModel = {
            actionTarget: 'SINGLEKEY',
			reloadData: false,
			refreshMode: 0,
			entityCodeName: 'IBIZOrder',
			keyFieldCodeName: 'IBIZOrderId',
            majorFieldCodeName: 'IBIZOrderName',
			closeEditView: false,
			navContexts: { 'contextparam1':'%ibizorderid%' },
			navParams: { 'param2':'%ibizorderid%' },
		};
		// 根据行为目标 合并行为参数
		const { context, viewParams, data } = await this.handleUIActionParam(uiContext, uiViewParams, uiData, actionModel);
    	try {
    		if (ability && hasFunction(ability, 'validate') && (actionModel.actionTarget=='SINGLEDATA' || actionModel.actionTarget=='MULTIDATA')) {
    			//	校验(暂时只考虑表格与表单)
    			if (!(await (ability as any).validate())) {
    				//	提示信息待确认
    				return { ok: false, data: [] };
    			}
    		}
    		//  获取实体服务
    		const dataService = await App.getDataService('IBIZOrder', context);
    		if (context.srfsessionid) {
    			Object.assign(context, { srfsessionkey: context.srfsessionid });
    			delete context.srfsessionid;
    		}
    	    const tempData = data[0];
    		const response: IHttpResponse = await dataService['Update'](context, tempData);
    		if (!response.success) {
    			App.getNotificationHelper().error(App.ts('common.generic.error'),response.message || '');
    			return { ok: false, data: [] };
    		}
    		App.getNotificationHelper().success('成功', '后台界面行为（保存）执行成功');
    		return await this.afterAction(context, viewParams, response.data, event, ability, actionModel);
    	} catch (error: any) {
    		App.getNotificationHelper().error(App.ts('common.generic.error'),error.message || '');
    	  	return { ok: false, data: error };
    	}
  }

	/**
	 * 删除
	 *
	 * @param {*} params
	 * @memberof IBIZOrderUIServiceBase
	 */
  public async Delete(
    uiContext: IContext,
    uiViewParams: IParam,
    uiData: IParam[],
    event: MouseEvent,
    ability: IAbility
  ): Promise<IUIActionResult> {
        const actionModel: IActionModel = {
            actionTarget: 'SINGLEKEY',
			reloadData: true,
			refreshMode: 1,
			entityCodeName: 'IBIZOrder',
			keyFieldCodeName: 'IBIZOrderId',
            majorFieldCodeName: 'IBIZOrderName',
			closeEditView: false,
		};
		// 根据行为目标 合并行为参数
		const { context, viewParams, data } = await this.handleUIActionParam(uiContext, uiViewParams, uiData, actionModel);
    	try {
    		const confirmResult = await new Promise<boolean>((resolve: Function) => {
    			App.getDialogHelper().confirm('警告', `是否确认需要删除当前数据？`, () => resolve(true), () => resolve(false));
    		});
    		if (!confirmResult) {
    			return { ok: false, data: [] };
    		}
    		if (ability && hasFunction(ability, 'validate') && (actionModel.actionTarget=='SINGLEDATA' || actionModel.actionTarget=='MULTIDATA')) {
    			//	校验(暂时只考虑表格与表单)
    			if (!(await (ability as any).validate())) {
    				//	提示信息待确认
    				return { ok: false, data: [] };
    			}
    		}
    		//  获取实体服务
    		const dataService = await App.getDataService('IBIZOrder', context);
    		if (context.srfsessionid) {
    			Object.assign(context, { srfsessionkey: context.srfsessionid });
    			delete context.srfsessionid;
    		}
    	    const tempData = data[0];
    		const response: IHttpResponse = await dataService['Remove'](context, tempData);
    		if (!response.success) {
    			App.getNotificationHelper().error(App.ts('common.generic.error'),response.message || '');
    			return { ok: false, data: [] };
    		}
    		App.getNotificationHelper().success('成功', '成功删除数据！');
    		return await this.afterAction(context, viewParams, response.data, event, ability, actionModel);
    	} catch (error: any) {
    		App.getNotificationHelper().error(App.ts('common.generic.error'),error.message || '');
    	  	return { ok: false, data: error };
    	}
  }

	/**
	 * 前台界面行为（编辑）
	 *
	 * @param {*} params
	 * @memberof IBIZOrderUIServiceBase
	 */
  public async FUIAction1(
    uiContext: IContext,
    uiViewParams: IParam,
    uiData: IParam[],
    event: MouseEvent,
    ability: IAbility
  ): Promise<IUIActionResult> {
        const actionModel: IActionModel = {
            actionTarget: 'NONE',
			reloadData: false,
			refreshMode: 0,
			entityCodeName: 'IBIZOrder',
			keyFieldCodeName: 'IBIZOrderId',
            majorFieldCodeName: 'IBIZOrderName',
			closeEditView: false,
			navContexts: { 'ibizorderid':'15c8e85a50dae2893c26945df5b58e4e','contextparam1':'%ibizorderid%','ibizorder':'15c8e85a50dae2893c26945df5b58e4e' },
			navParams: { 'param2':'%ibizorderid%' },
		};
		// 根据行为目标 合并行为参数
		const { context, viewParams, data } = await this.handleUIActionParam(uiContext, uiViewParams, uiData, actionModel);
    	// 根据视图名称 获取视图详情
    	const view = App.getAppViewConfig()['IBIZOrderEditView'];
    	if (!view) {
    		App.getNotificationHelper().warning('', '目标视图不存在');
    		return { ok: false, data: [] };
    	}
    	// 打开视图
    	const actionResult = await App.getOpenViewHelper().openPage(view, context, viewParams);
    	if (actionResult && actionResult.ok) {
    		return await this.afterAction(context, viewParams, data, event, ability, actionModel);
    	} else {
    		return { ok: false, data: [] };
    	}
  }

	/**
	 * 删除
	 *
	 * @param {*} params
	 * @memberof IBIZOrderUIServiceBase
	 */
  public async ZDYUpdate(
    uiContext: IContext,
    uiViewParams: IParam,
    uiData: IParam[],
    event: MouseEvent,
    ability: IAbility
  ): Promise<IUIActionResult> {
        const actionModel: IActionModel = {
            actionTarget: 'SINGLEKEY',
			reloadData: false,
			refreshMode: 0,
			entityCodeName: 'IBIZOrder',
			keyFieldCodeName: 'IBIZOrderId',
            majorFieldCodeName: 'IBIZOrderName',
			closeEditView: false,
		};
		// 根据行为目标 合并行为参数
		const { context, viewParams, data } = await this.handleUIActionParam(uiContext, uiViewParams, uiData, actionModel);
    	try {
    		if (ability && hasFunction(ability, 'validate') && (actionModel.actionTarget=='SINGLEDATA' || actionModel.actionTarget=='MULTIDATA')) {
    			//	校验(暂时只考虑表格与表单)
    			if (!(await (ability as any).validate())) {
    				//	提示信息待确认
    				return { ok: false, data: [] };
    			}
    		}
    		//  获取实体服务
    		const dataService = await App.getDataService('IBIZOrder', context);
    		if (context.srfsessionid) {
    			Object.assign(context, { srfsessionkey: context.srfsessionid });
    			delete context.srfsessionid;
    		}
    	    const tempData = data[0];
    		const response: IHttpResponse = await dataService['Remove'](context, tempData);
    		if (!response.success) {
    			App.getNotificationHelper().error(App.ts('common.generic.error'),response.message || '');
    			return { ok: false, data: [] };
    		}
    		return await this.afterAction(context, viewParams, response.data, event, ability, actionModel);
    	} catch (error: any) {
    		App.getNotificationHelper().error(App.ts('common.generic.error'),error.message || '');
    	  	return { ok: false, data: error };
    	}
  }

	/**
	 * 多项数据主键保存
	 *
	 * @param {*} params
	 * @memberof IBIZOrderUIServiceBase
	 */
  public async mulUpdate(
    uiContext: IContext,
    uiViewParams: IParam,
    uiData: IParam[],
    event: MouseEvent,
    ability: IAbility
  ): Promise<IUIActionResult> {
        const actionModel: IActionModel = {
            actionTarget: 'MULTIKEY',
			reloadData: false,
			refreshMode: 0,
			entityCodeName: 'IBIZOrder',
			keyFieldCodeName: 'IBIZOrderId',
            majorFieldCodeName: 'IBIZOrderName',
			closeEditView: false,
			navParams: { 'ordertype':'%ordertype%','orderstate':'%orderstate%' },
		};
		// 根据行为目标 合并行为参数
		const { context, viewParams, data } = await this.handleUIActionParam(uiContext, uiViewParams, uiData, actionModel);
    	try {
    		if (ability && hasFunction(ability, 'validate') && (actionModel.actionTarget=='SINGLEDATA' || actionModel.actionTarget=='MULTIDATA')) {
    			//	校验(暂时只考虑表格与表单)
    			if (!(await (ability as any).validate())) {
    				//	提示信息待确认
    				return { ok: false, data: [] };
    			}
    		}
    		//  获取实体服务
    		const dataService = await App.getDataService('IBIZOrder', context);
    		if (context.srfsessionid) {
    			Object.assign(context, { srfsessionkey: context.srfsessionid });
    			delete context.srfsessionid;
    		}
    		const promiseArray: Promise<IHttpResponse>[] = [];
    		if (data && data.length > 0) {
    			const srfkeys = context['ibizorder'] ? context['ibizorder'].split(',') : [];
    			data.forEach((item: IParam, index: number) => {
    				const tempContext = deepCopy(context);
    				Object.assign(tempContext, { ibizorder: srfkeys[index] });
    				promiseArray.push(dataService['MulUpdate'](tempContext, item));
    			})
    		}
    		const response = await Promise.all(promiseArray);
    		if (!response) {
    			return { ok: false, data: [] };
    		}
    		const resultData: IParam[] = [];
    		if (response.length > 0) {
    			response.forEach((item: IHttpResponse) => {
    				resultData.push(item.data);
    			})
    		};
    		App.getNotificationHelper().success('成功', '批量修改成功');
    		return await this.afterAction(context, viewParams, resultData, event, ability, actionModel);
    	} catch (error: any) {
    		App.getNotificationHelper().error(App.ts('common.generic.error'),error.message || '');
    	  	return { ok: false, data: error };
    	}
  }

	/**
	 * 打开文档
	 *
	 * @param {*} params
	 * @memberof IBIZOrderUIServiceBase
	 */
  public async open_document(
    uiContext: IContext,
    uiViewParams: IParam,
    uiData: IParam[],
    event: MouseEvent,
    ability: IAbility
  ): Promise<IUIActionResult> {
        const actionModel: IActionModel = {
            actionTarget: 'NONE',
			reloadData: false,
			refreshMode: 0,
			entityCodeName: 'IBIZOrder',
			keyFieldCodeName: 'IBIZOrderId',
            majorFieldCodeName: 'IBIZOrderName',
			closeEditView: false,
		};
		// 根据行为目标 合并行为参数
		const { context, viewParams, data } = await this.handleUIActionParam(uiContext, uiViewParams, uiData, actionModel);
    	window.open(
    		formatUrlString(
    			'https://www.yuque.com/ibiz/wuf19n/cwqg10',
    			context,
    			viewParams,
    			data && data.length ? data[0] : {}
    		),
    		'_blank'
    	);
    	return await this.afterAction(context, viewParams, data, event, ability, actionModel);
  }

	/**
	 * 界面逻辑
	 *
	 * @param {*} params
	 * @memberof IBIZOrderUIServiceBase
	 */
  public async panel_A424afda77415fcfb6f_button_calluilogic16_click(
    uiContext: IContext,
    uiViewParams: IParam,
    uiData: IParam[],
    event: MouseEvent,
    ability: IAbility
  ): Promise<IUIActionResult> {
		//	替换执行界面逻辑
		return await this.executeUILogic('OpenYuQue', uiContext, uiViewParams, uiData, event, ability);
  }

	/**
	 * 语雀文档
	 *
	 * @param {*} params
	 * @memberof IBIZOrderUIServiceBase
	 */
  public async panel_Usr1102678360_open_yuque_click(
    uiContext: IContext,
    uiViewParams: IParam,
    uiData: IParam[],
    event: MouseEvent,
    ability: IAbility
  ): Promise<IUIActionResult> {
		//	替换执行界面逻辑
		return await this.executeUILogic('OpenYuQue', uiContext, uiViewParams, uiData, event, ability);
  }

  /**
    * 获取指定数据的重定向页面
    * 
    * @param context 应用上下文 
    * @param viewParams 视图参数
    * @param data 业务数据
    * @param redirectParam 重定向视图输入参数
	* @memberof IBIZOrderUIServiceBase
    */
    public async getAppRDView(
        context: IContext,
		viewParams: IParam,
		data: IParam,
		redirectParam: IRedirectInput
    ){
        // 进行数据查询
        const service = await App.getDataService("IBIZOrder", context);
        const tempContext: IContext = deepCopy(context);
        const key: string = 'ibizorder';
        let srfkey: string | null = null;
        if (data && data.hasOwnProperty(key)) {
            srfkey = data[key];
        } else if (context && context[key]) {
            srfkey = context[key];
        } else if (viewParams && viewParams[key]) {
            srfkey = viewParams[key];
        }
        Object.assign(tempContext, { [key]: srfkey });
        let result: any;
        if (redirectParam.redirectAction && service[redirectParam.redirectAction] && service[redirectParam.redirectAction] instanceof Function) {
            result = await service[redirectParam.redirectAction](tempContext, data);
        } else {
            result = await service.Get(tempContext, data);
        }
        const curData:any = result.data;
        // 判断当前数据模式,默认为true,todo
        const iRealDEModel:boolean = true;
        let bDataInWF: boolean = false;
		let bWFMode:any = false;
		if (redirectParam.isEnableWorkflow) {
            return this.getWFView();
        } else {
            if (viewParams && viewParams.srfwf && this.InWorkflowArray.indexOf(viewParams.srfwf) !== -1) {
                return this.getWFView();
            }
        }
        let strPDTViewParam: string = await this.getDESDDEViewPDTParam(curData, bDataInWF, bWFMode);
        return this.allViewMap.get(strPDTViewParam);
    }

	/**
	 * 获取实体单数据实体视图预定义参数
	 *
	 * @param curData 当前数据
	 * @param bDataInWF 是否有数据在工作流中
	 * @param bWFMode   是否工作流模式
	 * @memberof IBIZOrderUIServiceBase
	 */
	public async getDESDDEViewPDTParam(
		curData: any,
		bDataInWF: boolean,
		bWFMode: boolean
	) {
		let strPDTParam: string = '';
		if (bDataInWF) {
			// TODO 判断数据是否在流程中
		}
		// TODO 多表单
		const multiFormDEField: string | null = null;

		const isApp = App.getProjectSetting().isApp;
		if (multiFormDEField) {
			const objFormValue: string = curData[multiFormDEField];
			if (isApp) {
				return 'MOBEDITVIEW:' + objFormValue;
			}
			return 'EDITVIEW:' + objFormValue;
		}
		if (isApp) {
			if (this.getDEMainStateTag(curData)) {
				return `MOBEDITVIEW:MSTAG:${this.getDEMainStateTag(curData)}`;
			}
			return 'MOBEDITVIEW:';
		}
		if (this.getDEMainStateTag(curData)) {
			return `EDITVIEW:MSTAG:${this.getDEMainStateTag(curData)}`;
		}
		return 'EDITVIEW:';
	}

  /**
    * 执行界面逻辑
    * @param logicTag 界面逻辑标识
    * @param context 应用上下文 
    * @param viewParams 视图参数
    * @param data 业务数据
    * @param event 事件对象
    * @param ability 当前环境能力
	* @memberof IBIZOrderUIServiceBase
    */
  public async executeUILogic<T extends IAbility>(logicTag: string, context: IContext, viewParams: IParam, data: IParam[], event: MouseEvent, ability: T): Promise<IUIActionResult> {
		if (logicTag === "GridViewLoad") {
			return await GridViewLoadUILogic.getInstance().execute(context, viewParams, data[0], event, ability);
		}
		if (logicTag === "OpenYuQue") {
			return await OpenYuQueUILogic.getInstance().execute(context, viewParams, data[0], event, ability);
		}
		return { ok: true, data: null };
  }
}